package com.reactor;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

public class EchoReactor implements Runnable{

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    public EchoReactor() throws Exception{
        selector=Selector.open();
        serverSocketChannel=ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(1234),1024);
        SelectionKey key = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        key.attach(new AcceptorHandler(selector,serverSocketChannel));
    }
    @Override
    public void run() {

        while (true){
            try {
                if (selector.select() > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        System.out.println("...");
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        dispatch(key);
                    }


                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    private void dispatch(SelectionKey key) {
        Runnable runnable = (Runnable) key.attachment();
        runnable.run();
    }
}
